//
//  PictureSelectorViewController.swift
//  mySina
//
//  Created by mac on 15/12/26.
//  Copyright © 2015年 tz. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let rowCount:CGFloat = 5
private let margin:CGFloat = 5
private let maxImageCount = 9

class PictureSelectorViewController: UICollectionViewController {
    var imageList = [UIImage]()
    
    init() {
        let flowLayout = UICollectionViewFlowLayout()
        //计算每个cell的宽度
        let itemW = (screenW - (rowCount + 1) * margin) / rowCount
        flowLayout.itemSize = CGSizeMake(itemW, itemW)
        //左右间距
        flowLayout.minimumInteritemSpacing = margin
        //上下间距
        flowLayout.minimumLineSpacing = margin
        //设置组间距
        flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
        super.init(collectionViewLayout: flowLayout)
        //修改背景色
        collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(pictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! pictureSelectorCell
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        //设置数据源
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        cell.delegate = self
        return cell
    }
}
extension PictureSelectorViewController:pictureSelectorCellDelegate {
    func userWillChosePicture(cell: pictureSelectorCell) {
        //让已经存在图片的不可以被再次点击
        if cell.image != nil {
            print("已近有图片了")
            return
        }
        //1选择图片
        //得到图片选择器的控件
        let picker = UIImagePickerController()
        //model出对应的图片选择器
        presentViewController(picker, animated: true, completion: nil)
        // 2.设置图片选择器的代理
        //一旦指定了代理对象 之后 就需要程序员手动dismiss picker
        picker.delegate = self
        //设置允许编辑 上传用户头像的时候 需要打开
//        picker.allowsEditing = true
    }
    func userWillDeletePicture(cell: pictureSelectorCell) {
       
        //通过传值的cell，获取index
        if let index = collectionView?.indexPathForCell(cell) {
            //在数组中，删除对应的indexpath.item角标下得元素
            imageList.removeAtIndex(index.item)
            //操作完数据源，刷新数据
            collectionView?.reloadData()
        }
    }
}
extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    /**
    图片选择器的协议方法
    
    - parameter picker:      图片选择器本身
    - parameter image:       表示用户选择的图片
    - parameter editingInfo: 编辑信息
    */
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        print(editingInfo)
        //将获取的图片添加到数组中
        imageList.append(image)
        //刷新列表
        collectionView?.reloadData()
        //手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//定义协议
@objc protocol pictureSelectorCellDelegate:NSObjectProtocol {
    //定义协议方法
    //添加图片
    optional func userWillChosePicture(cell:pictureSelectorCell)
    //删除图片 -> 添加参数，把自己回调回去
    optional func userWillDeletePicture(cell:pictureSelectorCell)
}

class pictureSelectorCell:UICollectionViewCell {
    
    //MARK: 定义外部模型属性
    var image:UIImage? {
        didSet {
            //如果设置图片为空得时候，就隐藏删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    //按钮的响应事件
    @objc private func addBtnDidClick() {
        delegate?.userWillChosePicture?(self)
        
    }
    @objc private func deleteBtnDidClick() {
        delegate?.userWillDeletePicture?(self)
    }
    //声明一个代理对象
    weak var delegate:pictureSelectorCellDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //更新UI
    private func setupUI() {
        //添加子控件
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //添加约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        //绑定按钮的监听事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    private lazy var addBtn:UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
    private lazy var deleteBtn:UIButton = UIButton(imageName: nil, backImageName: "compose_photo_close")
}




